package com.System.LearnSystemStudent;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.System.LearnSystem.Result;
import com.System.LearnSystem.Student;
import com.System.LearnSystem.Token;
import com.System.LearnSystem.User;
import com.System.LearnSystem.sqlConnection;
import com.System.LearnSystemBasic.Login;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;

import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

class Message1 extends Student  //用于临时储存客户端发来的请求信息
{
	private String token;
	public void settoken(String token)
	{
		this.token = token;
	}
	public String gettoken()	
	{
		return token;
	}
}


@WebServlet("/stu/editmessage")
public class editMessage extends HttpServlet{
	public void doPut(HttpServletRequest req, HttpServletResponse res) throws IOException
	{
		StringBuilder json = new StringBuilder();//读取json请求
        BufferedReader reader = req.getReader();
        String line;
        while ((line = reader.readLine()) != null) {
            json.append(line);
        }
        String jsonStr = json.toString();     
        ObjectMapper objectMapper = new ObjectMapper();
        Message1 message = objectMapper.readValue(jsonStr, Message1.class);
        
        objectMapper.registerModule(new JavaTimeModule());//注册驱动保证序列化
        res.setContentType("application/json;charset=UTF-8");//设置响应格式
        PrintWriter out = res.getWriter();
        if(message.gettoken()!=null)
        {
        	if(Token.checkToken(message.gettoken())&&"STUDENT".equals(message.getRole()))//验证令牌和身份
        	{
        		
	        		if(message.getPassword()!=null)
	        		{	
	        			String sql = "UPDATE t_user SET password = ? WHERE username = ?;";
	        			
	        			try (Connection conn = sqlConnection.getConnection();PreparedStatement pstmt = conn.prepareStatement(sql))
	        			{			
	        				pstmt.setString(1,message.getPassword());//将对应信息替换？的位置
	        				pstmt.setString(2,message.getUsername());
	        				int Line = pstmt.executeUpdate();
	        				System.out.println("受影响的行数为："+Line);
	        			} catch (SQLException e) {
	        				System.err.println("SQL 错误码: " + e.getErrorCode());
	          		  		System.err.println("SQL 错误消息: " + e.getMessage());
	          		  		e.printStackTrace();
	        			}
	        		}
        			if(message.getPhone()!=null)
        			{
        				String sql = "UPDATE t_student SET phone = ? WHERE username = ?;";//预处理语句
        				
        				try (Connection conn = sqlConnection.getConnection();PreparedStatement pstmt = conn.prepareStatement(sql))
            			{			    				
            				pstmt.setString(1,message.getPhone());//将对应信息替换？的位置 
            				pstmt.setString(2,message.getUsername());
            				int Line = pstmt.executeUpdate();
            				System.out.println("受影响的行数为："+Line);
            			} catch (SQLException e) {
            				System.err.println("SQL 错误码: " + e.getErrorCode());
              		  		System.err.println("SQL 错误消息: " + e.getMessage());
              		  		e.printStackTrace();
            			}
        			}
        			
        			if(message.getEmail()!=null)
        			{
        				String sql = "UPDATE t_student SET email = ? WHERE username = ?;";
        				try (Connection conn = sqlConnection.getConnection();PreparedStatement pstmt = conn.prepareStatement(sql))
            			{			
            				pstmt.setString(1,message.getEmail());//将对应信息替换？的位置
            				pstmt.setString(2,message.getUsername());
            				int Line = pstmt.executeUpdate();
            				System.out.println("受影响的行数为："+Line);
            			} catch (SQLException e) {
            				System.err.println("SQL 错误码: " + e.getErrorCode());
              		  		System.err.println("SQL 错误消息: " + e.getMessage());
              		  		e.printStackTrace();
            			}
 
        			}	
        			
        			Student student = settingStudent(settingUser(message.getUsername()),message.getUsername());
        			Result<Student> resultst = Result.success(student);		//返回修改后的学生信息给前端
        			out.println(objectMapper.writeValueAsString(resultst));
          		}
        	else
        	{
        		Result<Object> result = Result.error(401,"非授权访问");
        		out.println(objectMapper.writeValueAsString(result));
        	}
        }
        else
        {
        	Result<Object> result = Result.error(401,"非授权访问");
        	out.println(objectMapper.writeValueAsString(result));
        }
	}

	public static User settingUser(String username)//实例化用户信息
    {
    	User user = new User();
    	String sql = "SELECT * FROM t_user where username =?";//检索信息的sql语句，用于比对用户输入的信息
    	try (Connection conn = sqlConnection.getConnection();PreparedStatement pstmt = conn.prepareStatement(sql)) 
	{
    		pstmt.setString(1, username);//将对应信息替换？的位置
    		
    		ResultSet rs = pstmt.executeQuery();
    		while(rs.next())//将信息存入对应成员
    		{
    			user.setId((long)rs.getInt("id"));
    			user.setRole(rs.getString("role"));
    			user.setCreateTime(rs.getTimestamp("create_time"));
    			user.setCreateTime(rs.getTimestamp("update_time"));
    			user.setPassword(rs.getString("password"));
    			user.setUsername(username);
    			if(rs.getInt("status")==1)
    			{
    				user.setStatus(1);
    			}
    			else
    			{
    				user.setStatus(0);
    			}			
    		}
		} catch (SQLException e) {
			System.err.println("SQL 错误码: " + e.getErrorCode());
  		  	System.err.println("SQL 错误消息: " + e.getMessage());
  		    e.printStackTrace();
		}
    	return user;
    }
	
	
	
	public static Student settingStudent(User user,String username)//实例化学生信息
    {
    	Student st = new Student(user);
    	String sql = "SELECT * FROM t_student where username =?;";//检索信息的sql语句，用于比对用户输入的信息
    	try (Connection conn = sqlConnection.getConnection();PreparedStatement pstmt = conn.prepareStatement(sql)) 
	{
    		pstmt.setString(1, username);//将对应信息替换？的位置  		
    		ResultSet rs = pstmt.executeQuery();
    		while(rs.next())//将信息存入对应成员
    		{
    			st.setDepartmentId(rs.getLong("department_id"));
    			st.setCreateTime(rs.getTimestamp("create_time"));
    			st.setCreateTime(rs.getTimestamp("update_time"));
    			st.setStudentNo(rs.getString("student_no"));
    			st.setName(rs.getString("name"));
    			st.setEmail(rs.getString("email"));
    			st.setPhone(rs.getString("phone"));
    		}
		} catch (SQLException e) {
			System.err.println("SQL 错误码: " + e.getErrorCode());
  		  	System.err.println("SQL 错误消息: " + e.getMessage());
  		    e.printStackTrace();
		}
    	return st;
    }

}


